package cn.edu.zut.project1.service.Impl;

import cn.edu.zut.project1.dto.OrdersDTO;
import cn.edu.zut.project1.enums.OrderStatusEnum;
import cn.edu.zut.project1.mapper.OrdersMapper;
import cn.edu.zut.project1.mapper.ProductMapper;
import cn.edu.zut.project1.mapper.UserMapper;
import cn.edu.zut.project1.pojo.Orders;
import cn.edu.zut.project1.pojo.Product;
import cn.edu.zut.project1.service.OrdersService;
import cn.edu.zut.project1.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;  // 需要查询商品信息
    @Autowired
    private MessageService messageService;

    @Autowired
    private UserMapper userMapper;

    // 生成唯一订单编号：ORD+yyyyMMdd+3位随机数
    private String generateOrderNo() {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String random = String.format("%03d", new Random().nextInt(1000));
        return "ORD" + date + random;
    }

    /**
     * 1.创建订单
     * @param ordersDTO 订单信息
     * @param buyerId 买家ID
     * @return 订单编号
     */
    @Override
    @Transactional // 事务：确保订单和商品状态同时修改
    public String createOrder(OrdersDTO ordersDTO, Integer buyerId) {
        // 1. 查询商品信息
        Integer productId = ordersDTO.getProductId();
        Product product = productMapper.selectById(productId);
        //检验商品是否存在
        if(product == null){
            throw new RuntimeException("商品不存在");
        }
        //检验商品的状态（必须为在售）
        if(product.getStatus() != 0){
            throw new RuntimeException("商品已下架或卖出");
        }
        //检验商品库存是否充足
        if(product.getInventory() < 1){
            throw new RuntimeException("商品库存不足");
        }
        // 4. 校验买家不能是卖家（不能买自己的商品）
        Integer sellerId = product.getUserId();
        if (sellerId.equals(buyerId)) {
            throw new RuntimeException("不能购买自己的商品");
        }
        // 5. 生成订单
        Orders orders = new Orders();
        orders.setOrderNo(generateOrderNo());  // 订单编号
        orders.setProductId(productId);  // 商品编号
        orders.setProductName(product.getName());  // 商品名称
        orders.setBuyerId(buyerId);  //买家id(HttpSession session)
        orders.setSellerId(sellerId); //卖家id
        orders.setPrice(product.getPrice());  // 下单时的价格
        orders.setStatus(OrderStatusEnum.PENDING_PAY.getCode());  // 初始状态：待付款

        //6.创建订单
        int rows = orderMapper.insert(orders);
        if(rows != 1){
            throw new RuntimeException("创建订单失败");
        }

        // 7. 锁定商品（可选：改为"已下单"状态，避免重复购买）
        productMapper.updateStatus(productId, 3);  // 3=已下单

        String msgContent = "你的商品 【" + product.getName() + "】已下单成功！";
        messageService.sendSystemMsg(orders.getSellerId(), orders.getOrderNo(), msgContent);

        return orders.getOrderNo();


    }

    //2.付款
    @Override
    @Transactional
    public void payOrder(String orderNo) {
        Orders orders = orderMapper.selectByOrderNo(orderNo);
        if(orders == null){
            throw new RuntimeException("订单不存在");
        }

        // 校验状态：必须是待付款
        if(!orders.getStatus().equals(OrderStatusEnum.PENDING_PAY.getCode())){
            throw new RuntimeException("订单状态错误(应该为待付款(0))");
        }

        // 更新状态为"已付款"，记录付款时间
        orders.setStatus(OrderStatusEnum.PAID.getCode());
        orders.setPayTime(LocalDateTime.now());
        orderMapper.updateStatus(orders);

        String msgContent = "订单【" + orderNo + "】买家已付款，金额：" + orders.getPrice() + "元，请尽快发货";
        messageService.sendSystemMsg(orders.getSellerId(), orders.getOrderNo(), msgContent);

    }

    // 3. 卖家发货

    @Override
    @Transactional
    public void shipOrder(String orderNo, Integer sellerId) {
        Orders orders = orderMapper.selectByOrderNo(orderNo);
        // 检验订单是否存在
        if(orders == null){
            throw new RuntimeException("订单不存在");
        }
        // 校验状态：必须是已付款
        if(!orders.getStatus().equals(OrderStatusEnum.PAID.getCode())){
            throw new RuntimeException("订单状态错误（应该为已付款(1)）");
        }

        // 校验卖家ID：必须是卖家
        if(!orders.getSellerId().equals(sellerId)){
            throw new RuntimeException("你无权发货");
        }

        // 更新状态为"已发货"
        orders.setStatus(OrderStatusEnum.SHIPPED.getCode());
        orderMapper.updateStatus(orders);

        String msgContent = "订单【" + orderNo + "】已发货，请注意查收";
        messageService.sendSystemMsg(orders.getBuyerId(), orders.getOrderNo(), msgContent);

    }

    //买家确认收货
    @Override
    @Transactional
    public void confirmOrder(String orderNo, Integer buyerId) {
        Orders orders = orderMapper.selectByOrderNo(orderNo);
        if(orders == null){
            throw new RuntimeException("订单不存在");
        }
        // 校验状态：必须是已发货
        if(!orders.getStatus().equals(OrderStatusEnum.SHIPPED.getCode())){
            throw new RuntimeException("订单状态错误（应该为已发货(2)）");
        }
        // 校验买家ID：必须是买家
        if(!orders.getBuyerId().equals(buyerId)){
            throw new RuntimeException("你无权确认收货");
        }
        // 确认收货，更新状态为"已完成"，记录完成时间
        orders.setStatus(OrderStatusEnum.COMPLETED.getCode());
        orders.setFinishTime(LocalDateTime.now());
        orderMapper.updateStatus(orders);

        // 同步更新商品为"已卖出"
        productMapper.updateStatus(orders.getProductId(), 1);  // 1=已卖出

        String msgContent = "订单【" + orderNo + "】已被买家接收";
        messageService.sendSystemMsg(orders.getSellerId(), orders.getOrderNo(), msgContent);

    }

    // 5. 取消订单
    @Override
    public void cancelOrder(String orderNo, Integer userId) {
        Orders orders = orderMapper.selectByOrderNo(orderNo);
        if(orders == null){
            throw new RuntimeException("订单不存在");
        }
        // 校验状态：必须是待付款或已付款
        if(!orders.getStatus().equals(OrderStatusEnum.PENDING_PAY.getCode()) ||
        ! orders.getStatus().equals(OrderStatusEnum.PAID.getCode())){
            throw new RuntimeException("订单状态错误（应该为待付款(0)或已付款(1)）");
        }
        // 校验用户ID：必须是买家或卖家
        if(!orders.getBuyerId().equals(userId) && !orders.getSellerId().equals(userId)){
            throw new RuntimeException("你无权取消订单");
        }

        // 取消订单，更新状态为"已取消"
        orders.setStatus(OrderStatusEnum.CANCELED.getCode());
        orderMapper.updateStatus(orders);

        // 同步更新商品为"在售"
        productMapper.updateStatus(orders.getProductId(), 0);

        if(orders.getBuyerId().equals(userId)){
            String msgContent = "订单【" + orderNo + "】已被买家取消";
            messageService.sendSystemMsg(orders.getSellerId(), orders.getOrderNo(), msgContent);
        }

        if(orders.getSellerId().equals(userId)){
            String msgContent = "订单【" + orderNo + "】已被卖家取消";
            messageService.sendSystemMsg(orders.getBuyerId(), orders.getOrderNo(), msgContent);
        }

    }

    // 6. 查询买家的订单列表
    @Override
    public List<Orders> getBuyerOrders(Integer buyerId) {
        return orderMapper.selectByBuyerId(buyerId);
    }

    // 7. 查询卖家的订单列表
    @Override
    public List<Orders> getSellerOrders(Integer sellerId) {
        return orderMapper.selectBySellerId(sellerId);
    }

    //8. 查询我作为买家的所有订单
    @Override
    public List<Orders> getMyBuyerOrders(Integer buyerId) {
        return orderMapper.selectAsBuyerOrders(buyerId);
    }

    //9. 获取我作为卖家的所有订单
    @Override
    public List<Orders> getMySellerOrders(Integer sellerId) {
        return orderMapper.selectAsSellerOrders(sellerId);
    }

}
